

#include <string.h>

/**
 * Compare two null-terminated strings
 * 
 * const char *s1 - string 1
 * const char *s2 - string 2
 * 
 * returns
 *   - 0 if s1 == s2
 *   - >0 if s1 > s2
 *   - <0 if s1 < s2
 */
int strcmp(const char *s1, const char *s2)
{
	while (*s1 != 0 && *s1 == *s2)
	{
		s1++;
		s2++;
	}
	return (*s1 - *s2);
}

/**
 * Compare two strings of length n
 * 
 * const char *s1 - string 1
 * const char *s2 - string 2
 * int n - number of bytes to compare
 * 
 * returns
 *   - 0 if s1 == s2
 *   - >0 if s1 > s2
 *   - <0 if s1 < s2
 */
int strncmp(const char *s1, const char *s2, int n)
{
	if (n <= 0) return 0;
	do
	{
		if (*s1 != *s2)
			 return (*s1 - *s2);
		s1++;
		s2++;
	} while (--n > 0);
	return 0;
}

/**
 * Returns the length of a null-terminated string
 * 
 * const char *s - null-terminated string
 * 
 * returns
 *   - length of the string
 */
int strlen(const char *s)
{
	int count = 0;
	while (*s++ != '\0') count++;
	
	return count;
}

/**
 * Zero-fill's a range of memory with byte-granularity
 * 
 * byte *addr - address to memory
 * size_t length - number of bytes to fill
 */
void bzero(byte *addr, size_t length)
{
	// TODO: replace with asm, probably "rep stosb"-like
	size_t i;
	for (i = 0; i < length; i++)
	{
		*(addr + i) = 0;
	}
}

/**
 * Zero-fill's a range of memory with dword-granularity
 * 
 * dword *addr - address to memory
 * size_t length - number of bytes to fill
 */
void dwzero(dword *addr, size_t length)
{
	size_t i;
	for(i = 0; i < length; i++)
	{
		*(addr + i) = 0;
	}
}

/**
 * Copy a string of bytes from one memory location to another
 * 
 * char *dest - destination address
 * const char *src - source string
 * 
 * returns - pointer to destination address
 */
char * strcpy(char *dest, const char *src)
{
	char *orig = dest;
	
	for (; (*dest = *src); ++dest, ++src);
	
	return orig;
}
